const { Document, Packer, Paragraph } = require("docx");
const fs = require("fs");
const path = require("path");
const fse = require("fs-extra");

// 配置目录结构(包含文件/文件夹定义)
const FOLDER_STRUCTURE = [
  { 
    type: "folder", 
    name: "01概念与术语",
    children: [
        { type: "file", name: "01概念与术语.docx" },
    ]
  },
  { 
    type: "folder", 
    name: "02页面规范说明",
    children: [
        { type: "file", name: "01设计原则.docx" },
        { type: "file", name: "02全局样式.docx" },
        { type: "file", name: "03基础组件.docx" },
        { type: "file", name: "04业务组件情.docx" },
        { type: "file", name: "05交互模式.docx" },
        { type: "file", name: "06页面布局.docx" }
    ]
  }
];

// 生成默认文档内容(网页5[5](@ref)的样式规范)
const generateDocx = async (fileName) => {
  const doc = new Document({
    sections: [{
      properties: {},
      children: [
        new Paragraph({
          text: fileName.replace(".docx", ""),
          heading: "Heading1",
          alignment: "center"
        })
      ]
    }]
  });
  return Packer.toBuffer(doc);
};

// 递归创建目录结构(网页8[8](@ref)的递归算法优化)
const createStructure = async (rootPath, structure) => {
  for (const item of structure) {
    const currentPath = path.join(rootPath, item.name);
    
    if (item.type === "folder") {
      await fse.ensureDir(currentPath);
      console.log(`📂 创建目录：${currentPath}`);
      
      if (item.children) {
        await createStructure(currentPath, item.children);
      }
    } else {
      await fse.ensureDir(path.dirname(currentPath));
      const buffer = await generateDocx(item.name);
      fs.writeFileSync(currentPath, buffer);
      console.log(`📄 生成文档：${currentPath}`);
    }
  }
};

// 主执行流程
(async () => {
  // 输出的文档名称
  const ROOT_DIR = path.join(__dirname, "1通用说明");
  
  try {
    await createStructure(ROOT_DIR, FOLDER_STRUCTURE);
    console.log(`✅ 生成完成，共创建：
    ├─ 9个操作文档
    ├─ 1个旅客信息子目录
    └─ 1个身份信息文档`);
  } catch (error) {
    console.error(`❌ 生成失败：${error.message}`);
  }
})();

// 启动 node index.js   